<?php

namespace App\Containers\AppSection\Moneybox\Tasks;

use App\Containers\AppSection\Moneybox\Data\Repositories\MoneyboxRepository;
use App\Containers\AppSection\Moneybox\Models\Moneybox;
use App\Ship\Exceptions\NotFoundException;
use App\Ship\Parents\Tasks\Task;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;

class SendDataTask extends Task
{
    protected Client $client;
    protected MoneyboxRepository $repository;

    public function __construct(Client $client, MoneyboxRepository $repository)
    {
        $this->client = $client;
        $this->repository = $repository;
    }

    public function run(int $id, string $hash, string $request): ResponseInterface
    {
        try {
            /** @var Moneybox $moneybox */
            $moneybox = $this->repository->find($id);
        } catch (Exception $exception) {
            throw new NotFoundException(__('ship::resource.not-found'));
        }

        try {
            return $this->client->post(config('appSection-moneybox.url') . $moneybox->method, [
                'body' => $request,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                    'Digital-Sign' => $hash,
                ],
            ]);
        } catch (GuzzleException $e) {
            $exception = "";
            if ($e->hasResponse()) {
                $exception = (string)$e->getResponse()->getBody();
            }
            throw new Exception($exception, $e->getCode());
        }
    }
}
